
package com.neusoft.neuiotms.dcom.repository.impl;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.model.QShift;
import com.neusoft.neuiotms.dcom.model.Shift;
import com.neusoft.neuiotms.dcom.model.enums.ShiftType;
import com.neusoft.neuiotms.dcom.repository.CustomizedShiftRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedShiftRepositoryImpl extends AbstractRepository implements CustomizedShiftRepository {

    @Override
    public List<Shift> index(final Searchable searchable) {
        final QShift qShift = QShift.shift;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Shift> query = this.query().selectFrom(qShift);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<Shift> search(final Pageable pageable, final Searchable searchable) {
        final QShift qShift = QShift.shift;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Shift> query = this.query().selectFrom(qShift);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return Shift.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {

        final BooleanBuilder where = new BooleanBuilder();
        final QShift qShift = QShift.shift;

        // 组织机构检索
        where.and(super.equalsStr(qShift.dutyArrangement.orgCode, searchable, "orgCode"));
        // in组织机构
        where.and(super.inStrings(qShift.dutyArrangement.orgCode, searchable, "orgCodes"));

        // 值班安排
        where.and(super.equalsLong(qShift.dutyArrangement.id, searchable, "dutyArrangementId"));

        // 人员编码
        where.and(super.equalsStr(qShift.sourceUserCode, searchable, "sourceUserCode"));
        where.and(super.equalsStr(qShift.targetUserCode, searchable, "targetUserCode"));

        // 日期检索时间段
        where.and(super.afterOrEqualsDate(qShift.startTime, searchable, "startTime"));
        where.and(super.beforeOrEqualsDate(qShift.startTime, searchable, "endTime"));

        // 换班日期检索时间段
        where.and(super.afterOrEqualsDate(qShift.shiftStartTime, searchable, "shiftStartTime"));
        where.and(super.beforeOrEqualsDate(qShift.shiftStartTime, searchable, "shiftEndTime"));

        // 状态
        where.and(super.equalsBool(qShift.status, searchable, "status"));

        // 类型
        where.and(super.equalsEnum(qShift.type, searchable, "type", value -> ShiftType.valueOf(value)));
        return where;
    }
}
